<template>
<div class="app-container">
  <header class="app-header">
    <span class="title">{{$route.meta.title}}</span>
  </header>
  <div class="course-class" style="padding:0 15px 40px;">
  	<el-row>
    	<el-col :span="12">
      	<SingleUpload ext='jpg/png/gif/jpeg' :imageUrl="imageUrl" @on-select="onSelect"></SingleUpload>
        <div class="pis-list">
        	<div class="pis-lis" @click="changeCurImgDx">
          	<div class="pis-li">
          		<i class="el-icon-circle-plus" style="font-size:50px; color:#F3F7FA;"></i>         
          	</div>          	
          </div>
        	<div v-for="(item,index) in formData.pics" class="pis-lis">
          	<div class="pis-li">
          		 <el-image fit="contain" lazy :src="item.url" @click="changeCurImg(index)" class="pis-li-img"></el-image>        
          	</div>
            <el-button-group class="tit-btn">
              <el-button type="primary" style=" width:50px;" icon="el-icon-edit" @click="editItemPic(index)" size="mini"></el-button>
              <el-button type="danger" style=" width:49px;" icon="el-icon-delete" @click="delItemPic(index)" size="mini"></el-button>
            </el-button-group>
          </div>
        </div>         
      </el-col>
      <el-col :span="12">
        <el-form  :model="formData" :rules="formRules" ref="dataForm">
          <el-form-item label="商品名称：" prop="name"  label-width="120px" >
            <el-input v-model.trim="formData.name"  placeholder="请输入商品名称" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="引导语：" prop="tips"  label-width="120px" >
            <el-input v-model.trim="formData.tips"  placeholder="请输入引导语" auto-complete="off"></el-input>
          </el-form-item> 
          <el-form-item label="所属分类：" prop="categories"  label-width="120px" >
            <el-cascader :options="categories" v-model="formData.categories" :props="cateProps" style="width:100%;" placeholder="请选择相关分类" @change="categoriesChange" ></el-cascader>
          </el-form-item> 
          <el-form-item label="所属属性：" prop="tags"  label-width="120px" >
            <el-cascader v-model="formData.tags" clearable :options="tags" style="width:100%;" placeholder="请选择相关属性" :props="tagProps"></el-cascader>
          </el-form-item>           
          <el-form-item label="商品价格：" prop="price"  label-width="120px" >
            <el-input-number v-model.trim="formData.price" :precision="2" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="市场价格：" prop="marketPrice"  label-width="120px" >
            <el-input-number v-model.trim="formData.marketPrice" :precision="2" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="库存：" prop="inventory"  label-width="120px" >
            <el-input-number v-model.trim="formData.inventory"></el-input-number>
          </el-form-item>                                     	
        </el-form>
      </el-col>
    </el-row>
  </div>	
  <header class="app-header">
    <span class="title">商品详情</span>
  </header>
  <Tinymce ref="editorDetail" v-model="formData.details" :height="500" class="editor" />
  <header class="app-header" style=" margin-top:30px;">
    <span class="title">商品描述</span>
  </header>
  <Tinymce ref="editorIntro" v-model="formData.introduce" :height="500" class="editor" />
  <div class="btns">
    <el-button type="primary" icon="el-icon-edit-outline" :loading="loading" @click.native="handleSave">保存并上线</el-button>
    <el-button type="warning" icon="el-icon-edit" :loading="loading" @click.native="handleSave">保存并复制该商品</el-button> 
    <el-button type="danger" icon="el-icon-delete" :loading="loading" @click.native="handleRelease">保存暂不上线</el-button>   
  </div>       
 </div>  
</div>
</template>
<script>
import config from '@/api/bgapi'
import request from '@/utils/request'
import SingleUpload from "@/components/Upload/SingleUploadShopCos";
import Tinymce from '@/components/Tinymce';
export default {
	components: { SingleUpload,Tinymce},
	data() {
		return {
			formData:{
				name:'',
				tips:'',
				price:'',
				marketPrice:'', //市场价
				inventory:0, //库存
				pics:[],//商品图 0
				categories:[],
				tags:[],
				status:1,
				introduce:'',
				details:''
			},
			formRules: {
				 name: [{ required: true, message: "请输入商品名称!", trigger: "blur"}],
				 categories:[{ required: true, message: "请选择主分类!", trigger: "blur"}]
			},
			categories:[],
			cateProps:{children: 'children', label: 'cateName' ,value:'id'},
			tags:[],
			tagProps:{children: 'children', label: 'tagName' ,value:'id',multiple: true},
			loading:false,
			imageUrl:'',
		}
	},
  mounted(){
		this.id = this.$route.query.id;
		this.editIndex = '';	
		this.setData();	
  },	
  methods: {
		goBack(){
			this.$router.back();
		},
		async setData(){
			let categories = await request.get(config.shopCate);
      if(categories.code == '20000'){
        this.categories = categories.data;
      };
			let tags = await request.get(config.shopTags);
      if(tags.code == '20000'){
        this.tags = tags.data;
      }
			let content = await request.get(config.goods,{ params:{id:this.id} });
			if(content.code == '20000'){
				var _content = content.data[0];
				console.log(_content);
				this.formData = {
					name:_content.name,
					tips:_content.tips,
					price:_content.price,
					marketPrice:_content.marketPrice, //市场价
					inventory:_content.inventory, //库存
					pics:_content.pics,//商品图 0
					categories:_content.categories,
					tags:_content.tags,
					status:_content.status,
					introduce:_content.introduce,
					details:_content.details
				}
			}
		},
		categoriesChange(value){
			this.formData.categories = value;
		},
		tagsChange(value){
			this.formData.tags = value;
		},		
		
		onSelect(data){
			if(this.editIndex === ''){
				var _obj = {
					url:data.imgUrl,
					sort: this.formData.pics.length+1
				}	
				this.formData.pics.push(_obj);
			}else{
				var _index = this.editIndex;
				this.editIndex = '';
				this.formData.pics[_index].url = data.imgUrl;
				this.imageUrl = data.imgUrl;
			}
		},
		changeCurImg(_index){
			this.imageUrl = this.formData.pics[_index].url;	
		},
		changeCurImgDx(){
			this.imageUrl = '';	
		},
		delItemPic(_index){
			this.formData.pics.splice(_index, 1);	
		},
		editItemPic(_index){
			this.editIndex = _index;
			document.querySelector('.el-upload__input').click();
		},
    resetForm() {
      if (this.$refs["dataForm"]) {
        // 清空验证信息表单
        this.$refs["dataForm"].clearValidate();
        // 刷新表单
        this.$refs["dataForm"].resetFields();
      	this.$refs.editorDetail.setContent('');
				this.$refs.editorIntro.setContent('');
				this.formData.pics = [];
				this.imageUrl = '';
				
			}
    },			
		handleSave(){
			this.$refs["dataForm"].validate(async valid => {
				if(valid){
					this.formData.status = 1;
					var res = await request.put(config.goods+'/'+this.id,this.formData);
					if(res.code == '20000'){
						this.$message.success('保存成功！');
					}else{
						this.$message.error('保存失败，请联系管理员！');	
					}
				}	
			})	
		},
		handleRelease(){
			this.$refs["dataForm"].validate(async valid => {
				if(valid){
					//this.formData.titleImg = 
					this.formData.status = 0;
					var res = await request.put(config.goods+'/'+this.id,this.formData);
					if(res.code == '20000'){
						this.$message.success('保存成功！');
					}else{
						this.$message.error('保存失败，请联系管理员！');	
					}
				}	
			})			
		}		
		
		
		
	}
}
</script>
<style scoped>
.editor-content { margin-top: 20px;}
.pis-box{ height:330px; width:100%; display:flex; text-align:center; align-items:center; margin-bottom:20px;}
.pics{ width:100%; text-align:center;}
.pis-list{ width:100%; height:150px;display:flex; justify-content:flex-start; margin-top:20px;}
.pis-lis{ width:100px; height:150px; margin-right:15px;}
.pis-li{ width:100px; height:100px;  margin-bottom:15px;  display:flex; text-align:center; align-items:center; border:1px solid #E4EBF5; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);}
.pis-li-img{ max-width:100px; max-height:100px; cursor:pointer;}
.el-icon-picture-outline,.el-icon-circle-plus{ display:block; margin:0 auto; cursor:pointer;}
.tit-btn{width:100px;}
.btns{ padding:35px 0 50px;}
</style>